package com.infra.micro.quartz.domain.service.impl;

import com.infra.micro.quartz.domain.config.BizConfig;
import com.infra.micro.quartz.domain.entity.QuartzJobLogPO;
import com.infra.micro.quartz.domain.service.JobAlarmService;
import com.infra.micro.quartz.model.vo.QuartzJobVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;


@Service("jobEmailAlarmService")
public class JobEmailAlarmServiceImpl implements JobAlarmService {
    @Resource
    private TemplateEngine templateEngine;
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private BizConfig bizConfig;

    @Override
    public String getAlarmMode() {
        return "email";
    }

    @Override
    public boolean send(QuartzJobVO jobDetail, QuartzJobLogPO logDetail) throws Exception {
        if (StringUtils.isBlank(jobDetail.getAlarmEmail())) {
            return true;
        }

        Context context = new Context();
        context.setVariable("logDetail", logDetail);

        String contentText = templateEngine.process("/alarm-email-template", context);

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setFrom(bizConfig.getFrom(), "调度任务预警服务");
        helper.setTo(jobDetail.getAlarmEmail());
        helper.setSubject(String.format("[调度任务预警]{}", jobDetail.getJobName()));
        helper.setText(contentText, true);

        javaMailSender.send(mimeMessage);
        return false;
    }
}
